package com.zwb.crasher;

import android.content.Context;
import android.os.Environment;

import com.zwb.crasher.log.CrashCatcher;
import com.zwb.crasher.log.CrashListener;

import java.io.File;

/**
 * Created by jasonchou on 15/7/13.
 */
public class WbCrasher {
    private static WbCrasher instance = new WbCrasher();

    private CrashListener mReporter;
    private String mLogFileName;
    private boolean mRealTimeUpload = false;
    private boolean mStoreInSDCard = true;

    private WbCrasher() {

    }

    public void init(Context context) {
        if (mLogFileName == null) {
            mLogFileName = "WbCrasher.log";
        }

        File logFile = getLogFile(context, mStoreInSDCard, mLogFileName);
        CrashCatcher.getInstance().init(logFile, mReporter);

        Thread.setDefaultUncaughtExceptionHandler(CrashCatcher.getInstance());
    }

    public static WbCrasher getInstance() {
        return instance;
    }

    public static WbCrasher share(WbCrasher crasher) {
        instance = crasher;
        return instance;
    }

    public void share() {
        instance = this;
    }

//
//    public void uploadLog() {
//        if (mReporter != null)
//            mReporter.send();
//    }

    protected static final File getLogFile(Context context, boolean sdcard, String name) {
        if (!sdcard)
            return new File(context.getFilesDir(), name);

        File file = new File(getSDCardDir(), name);
        return file;
    }

    private static String getSDCardDir() {
        StringBuilder sb = new StringBuilder();
        sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
        sb.append(File.separator);
        return sb.toString();
    }

    public static class Builder {
        private Context context;
        private String logFileName;
        private CrashListener reporter;
        private boolean realTimeUpload;
        private boolean storeInSDCard = true;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setLogFile(String fileName) {
            logFileName = fileName;
            return this;
        }

        public Builder realTimeUpload() {
            this.realTimeUpload = true;
            return this;
        }

        public Builder storeInSDCard() {
            this.storeInSDCard = true;
            return this;
        }

        public Builder setReporter(CrashListener reporter) {
            this.reporter = reporter;
            return this;
        }

        public WbCrasher build() {
            WbCrasher wbCrasher = new WbCrasher();
            wbCrasher.mLogFileName = logFileName;
            wbCrasher.mReporter = reporter;
            wbCrasher.mRealTimeUpload = realTimeUpload;
            wbCrasher.mStoreInSDCard = storeInSDCard;
            wbCrasher.init(context);
            return wbCrasher;
        }
    }
}
